<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE流式输出调试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background: #0056b3;
        }
        .output {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
            white-space: pre-wrap;
        }
        .log {
            background: #2d3748;
            color: #e2e8f0;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>SSE流式输出调试</h1>
        
        <div class="form-group">
            <label for="baseUrl">服务端地址:</label>
            <input type="text" id="baseUrl" value="http://localhost:8080">
        </div>
        
        <div class="form-group">
            <label for="message">测试消息:</label>
            <input type="text" id="message" value="你好，请介绍一下你自己">
        </div>
        
        <div class="form-group">
            <label for="sessionId">会话ID (可选):</label>
            <input type="text" id="sessionId" placeholder="SSE会话ID">
        </div>
        
        <div class="form-group">
            <label for="agentId">代理ID (可选):</label>
            <input type="text" id="agentId" value="8b44308c-5f29-4490-b7eb-46ca36ead41b" placeholder="AI代理ID">
        </div>
        
        <div class="form-group">
            <button onclick="testStream()">测试流式输出</button>
            <button onclick="testChatStream()">测试聊天流</button>
            <button onclick="clearOutput()">清空输出</button>
        </div>
        
        <div class="form-group">
            <label>流式输出结果:</label>
            <div id="output" class="output"></div>
        </div>
        
        <div class="form-group">
            <label>调试日志:</label>
            <div id="log" class="log"></div>
        </div>
    </div>

    <script>
        function log(message) {
            const logEl = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            logEl.textContent += `[${timestamp}] ${message}\n`;
            logEl.scrollTop = logEl.scrollHeight;
        }

        function appendOutput(content) {
            const outputEl = document.getElementById('output');
            const timestamp = new Date().toLocaleTimeString();
            outputEl.textContent += `[${timestamp}] ${content}\n`;
            outputEl.scrollTop = outputEl.scrollHeight;
        }

        function clearOutput() {
            document.getElementById('output').textContent = '';
            document.getElementById('log').textContent = '';
        }

        async function testStream() {
            const baseUrl = document.getElementById('baseUrl').value.trim();
            const message = document.getElementById('message').value.trim();
            const sessionId = document.getElementById('sessionId').value.trim();
            
            if (!baseUrl || !message) {
                alert('请填写服务端地址和测试消息');
                return;
            }
            
            try {
                log('开始测试流式输出...');
                clearOutput();
                appendOutput('开始连接流式输出...');
                
                const requestData = {
                    desc: message
                };
                
                const url = `${baseUrl}/api/client/index/generateUserLocation?sessionId=${encodeURIComponent(sessionId || '')}`;
                log(`请求URL: ${url}`);
                log(`请求数据: ${JSON.stringify(requestData)}`);
                
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream',
                        'Cache-Control': 'no-cache'
                    },
                    body: JSON.stringify(requestData)
                });
                
                log(`响应状态: ${response.status} ${response.statusText}`);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorText}`);
                }
                
                log('开始读取流式响应...');
                appendOutput('连接成功，开始接收数据...');
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let lineCount = 0;
                let totalBytes = 0;
                let chunkCount = 0;
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) {
                        log('流式输出完成');
                        appendOutput('[完成] 流式输出结束');
                        break;
                    }
                    
                    chunkCount++;
                    const newChunk = decoder.decode(value, { stream: true });
                    buffer += newChunk;
                    totalBytes += value.length;
                    
                    log(`接收到第${chunkCount}个数据块: ${newChunk.length} 字符，总计: ${totalBytes} 字节`);
                    
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (line.trim()) {
                            lineCount++;
                            log(`处理第${lineCount}行: ${line.substring(0, 100)}...`);
                            appendOutput(line);
                        }
                    }
                    
                    if (buffer && !buffer.includes('\n')) {
                        log(`显示缓冲区内容: ${buffer}`);
                        appendOutput(buffer);
                        buffer = '';
                    }
                }
                
                log(`流式处理完成，共接收${chunkCount}个数据块，处理${lineCount}行，总计${totalBytes}字节`);
                
            } catch (error) {
                log(`流式输出测试失败: ${error.message}`);
                appendOutput(`[错误] ${error.message}`);
            }
        }

        async function testChatStream() {
            const baseUrl = document.getElementById('baseUrl').value.trim();
            const message = document.getElementById('message').value.trim();
            const sessionId = document.getElementById('sessionId').value.trim();
            const agentId = document.getElementById('agentId').value.trim();
            
            if (!baseUrl || !message) {
                alert('请填写服务端地址和测试消息');
                return;
            }
            
            try {
                log('开始测试聊天流...');
                clearOutput();
                appendOutput('开始连接聊天流...');
                
                const requestData = {
                    desc: message
                };
                
                const url = `${baseUrl}/api/client/index/testChatStream?sessionId=${encodeURIComponent(sessionId || '')}&agentId=${encodeURIComponent(agentId || '')}`;
                log(`请求URL: ${url}`);
                log(`请求数据: ${JSON.stringify(requestData)}`);
                
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream',
                        'Cache-Control': 'no-cache'
                    },
                    body: JSON.stringify(requestData)
                });
                
                log(`响应状态: ${response.status} ${response.statusText}`);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorText}`);
                }
                
                log('开始读取聊天流响应...');
                appendOutput('连接成功，开始接收聊天数据...');
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let lineCount = 0;
                let totalBytes = 0;
                let chunkCount = 0;
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) {
                        log('聊天流输出完成');
                        appendOutput('[完成] 聊天流输出结束');
                        break;
                    }
                    
                    chunkCount++;
                    const newChunk = decoder.decode(value, { stream: true });
                    buffer += newChunk;
                    totalBytes += value.length;
                    
                    log(`接收到第${chunkCount}个数据块: ${newChunk.length} 字符，总计: ${totalBytes} 字节`);
                    
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (line.trim()) {
                            lineCount++;
                            log(`处理第${lineCount}行: ${line.substring(0, 100)}...`);
                            appendOutput(line);
                        }
                    }
                    
                    if (buffer && !buffer.includes('\n')) {
                        log(`显示缓冲区内容: ${buffer}`);
                        appendOutput(buffer);
                        buffer = '';
                    }
                }
                
                log(`聊天流处理完成，共接收${chunkCount}个数据块，处理${lineCount}行，总计${totalBytes}字节`);
                
            } catch (error) {
                log(`聊天流测试失败: ${error.message}`);
                appendOutput(`[错误] ${error.message}`);
            }
        }
    </script>
</body>
</html> 